<template>
  <a-spin :spinning="loading" style="overflow-y:auto">
    <a-card :bordered="false" style="margin-bottom: 24px;">
      <a-form :form="form">
        <a-form-item
          :label="$t('messageCenter.app.tempCode')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-bind="validator.codeValidProps"
        >
          <s-input
            :disabled="!!id || !canEdit"
            v-decorator="[
              'code',
              {
                rules: [
                  {
                    validator: validator.codeValidator
                  }
                ]
              }
            ]"
            :limit="128"
          />
        </a-form-item>
        <a-form-item :label="$t('common.type')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            :disabled="!canEdit"
            v-decorator="[
              'type',
              {
                rules: [
                  {
                    required: true,
                    message: $t('common.emptyErr', {
                      name: $t('common.type')
                    })
                  }
                ]
              }
            ]"
            style="width: 90%; display: inline-block; margin-right: 12px;"
          >
            <a-select-option v-for="(t, index) in types" :key="index" :value="t.name">{{ t.name }}</a-select-option>
          </a-select>
          <a
            v-action:save
            href="javascript:;"
            :style="{ display: 'inline-block', width: 'calc(10% - 12px)' }"
            @click="$refs.typeForm.add()"
          ><a-icon
            type="plus"
          /></a>
        </a-form-item>
        <a-form-item :label="$t('common.description')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <s-textarea :disabled="!canEdit" v-decorator="['description']" :limit="200" />
        </a-form-item>
      </a-form>
    </a-card>

    <a-card :bordered="false" style="margin-bottom: 24px;">
      <div class="table-operator">
        <a-button
          v-action:save
          type="primary"
          icon="plus"
          @click="$refs.varForm.add(id)"
        >{{ $t('button.add') }}
        </a-button>
      </div>
      <a-table
        ref="table"
        :columns="columns"
        :dataSource="templateVarConfigs"
        rowKey="tempId"
        pageURI
        :scroll="{ x: 1200 }"
        :pagination="false"
      >
        <template slot="action" slot-scope="text, record">
          <a v-action:save href="javascript:;" @click="$refs.varForm.edit(record)">{{ $t('common.edit') }}</a>
          <a-divider v-action:save type="vertical" />
          <a v-action:save href="javascript:;" @click="onDeleteVarConfig(record.tempId)">{{ $t('common.delete') }}</a>
        </template>
      </a-table>
    </a-card>

    <a-card :bordered="false" style="margin-bottom: 64px;">
      <a-tabs>
        <a-tab-pane key="mail" :tab="$t('modules.common.mail')">
          <a-form-item :label="$t('common.title')">
            <s-input :disabled="!canEdit" v-model="templateConfig.mailTitle" :limit="200"></s-input>
          </a-form-item>
          <div class="edit-container">
            <quill-editor
              :disabled="!canEdit"
              style="height:100%"
              v-model="templateConfig.mail"
              ref="myQuillEditor"
              :options="editorOption"
            />
          </div>
        </a-tab-pane>
        <a-tab-pane key="wechat" :tab="$t('modules.common.wechatWork')">
          <a-form-item :label="$t('common.title')">
            <s-input :disabled="!canEdit" v-model="templateConfig.wechatTitle" :limit="200"></s-input>
          </a-form-item>
          <a-textarea :disabled="!canEdit" v-model="templateConfig.wechat" :rows="4"></a-textarea>
        </a-tab-pane>
        <a-tab-pane key="notice" :tab="$t('modules.common.sysMsg')">
          <a-form-item :label="$t('common.title')">
            <s-input :disabled="!canEdit" v-model="templateConfig.noticeTitle" :limit="200"></s-input>
          </a-form-item>
          <a-textarea :disabled="!canEdit" v-model="templateConfig.notice" :rows="4"></a-textarea>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <footer-tool-bar v-action:save>
      <a-button type="primary" @click="handleSubmit" :loading="confirmLoading">{{ $t('common.submit') }}</a-button>
    </footer-tool-bar>
    <type-form ref="typeForm" @ok="onSubmitType" />
    <var-form ref="varForm" @ok="onSubmitVarConfig" />
  </a-spin>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { asyncValidateMixin } from '@/utils/mixin'
import { uuidv4 } from '@/utils/util'
import { getTempTypeList } from '@/api/messageCenter/mos'
import { getTemplate, createTemplate, updateTemplate, validateTemp } from '@/api/messageCenter/template'

import FooterToolBar from '@/components/FooterToolbar'
import { SInput, STextarea } from '@/components'

import VarForm from './VarForm'
import TypeForm from './TypeForm'
export default {
  name: 'TemplateDetail',
  components: {
    FooterToolBar,
    SInput,
    STextarea,
    quillEditor,
    VarForm,
    TypeForm
  },
  mixins: [asyncValidateMixin],
  data () {
    return {
      labelCol: {
        lg: { span: 7 },
        sm: { span: 7 }
      },
      wrapperCol: {
        lg: { span: 10 },
        sm: { span: 17 }
      },
      loading: false,
      id: 0,
      types: [],
      form: this.$form.createForm(this),
      confirmLoading: false,
      templateVarConfigs: [],
      templateConfig: {},
      editorOption: {
        // some quill options
        placeholder: this.$t('common.plzInput')
      },
      canEdit: this.$auth('save', this.$route.meta.permissionId)
    }
  },
  computed: {
    columns () {
      let colums = [
        {
          title: this.$t('messageCenter.app.varName'),
          dataIndex: 'varName'
        },
        {
          title: this.$t('common.description'),
          dataIndex: 'description'
        }
      ]
      if (this.$auth('save', this.$route.meta.permissionId)) {
        colums = colums.concat({
          title: this.$t('common.action'),
          dataIndex: 'action',
          width: 180,
          align: 'center',
          scopedSlots: { customRender: 'action' },
          fixed: 'right'
        })
      }
      return colums
    }
  },
  created () {
    const id = this.$route.params.id
    this.id = id
    this.init()
    this.initAsyncValidateMixin()
  },
  methods: {
    init () {
      this.getTypeList()
      if (this.id) {
        this.initTemplate(this.id)
      }
    },

    /**
     * 初始化验证器
     */
    initAsyncValidateMixin () {
      const validateFields = [
        {
          fieldName: 'code',
          caller: validateTemp,
          extraParams: {
            id: this.id
          }
        }
      ]
      this.$_asyncValidateMixin_init(validateFields)
    },

    getTypeList () {
      getTempTypeList().then(res => {
        this.types = res.data
      })
    },

    initTemplate (id) {
      this.loading = true
      getTemplate({ id })
        .then(res => {
          const { templateConfig, templateVarConfigs } = res.data
          if (templateConfig) {
            const {
              code,
              type,
              description,
              mail,
              mailTitle,
              notice,
              noticeTitle,
              wechat,
              wechatTitle
            } = templateConfig
            this.templateConfig = {
              mailTitle: mailTitle || '',
              mail: mail || '',
              noticeTitle: noticeTitle || '',
              notice: notice || '',
              wechatTitle: wechatTitle || '',
              wechat: wechat || ''
            }
            this.$nextTick(() => {
              this.form.setFieldsValue({
                code,
                type,
                description
              })
            })
          }
          this.templateVarConfigs = templateVarConfigs.map(ele => {
            ele.tempId = uuidv4()
            return ele
          })
        })
        .finally(() => {
          this.loading = false
        })
    },

    onSubmitType (values) {
      this.getTypeList()
    },

    onSubmitVarConfig (values) {
      const { id, formType, varName, description } = values
      if (values.formType === 'ADD') {
        this.templateVarConfigs.push({
          tempId: uuidv4(),
          id,
          varName,
          description
        })
      } else {
        this.templateVarConfigs = this.templateVarConfigs.map(ele => {
          if (ele.tempId === values.tempId) {
            ele.varName = values.varName
            ele.description = values.description
          }
          return ele
        })
      }
    },

    onDeleteVarConfig (tempId) {
      this.templateVarConfigs = this.templateVarConfigs.filter(ele => ele.tempId !== tempId)
    },

    handleSubmit () {
      if (this.templateVarConfigs.length === 0) {
        this.$notification.error({
          message: '错误',
          description: '内置变量不能为空'
        })
        return
      }
      const {
        form: { validateFields, getFieldsValue }
      } = this
      const fieldNames = this.id ? ['type'] : ['code', 'type']
      validateFields((errors, values) => {
        this.confirmLoading = true
        if (!errors) {
          const { code, type, description } = getFieldsValue()
          const model = {
            templateConfig: {
              ...this.templateConfig,
              code: code ? code.trim() : '',
              description: description ? description.trim() : '',
              type
            },
            templateVarConfigs: this.templateVarConfigs
          }
          if (!this.id) {
            createTemplate(model)
              .then(res => {
                this.$router.push({ name: 'template' })
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            model.templateConfig.id = this.id
            updateTemplate(model)
              .then(res => {
                this.$router.push({ name: 'template' })
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.edit-container {
  height: 200px;
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: left;
  color: #2c3e50;
  margin-top: 20px;
  margin-bottom: 66px;
}
</style>
